import 'package:hi_common/util/color.dart';
import 'package:hi_common/util/logger.dart';

import 'package:bilibili/widget/video_detail_card.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hi_net/http/core/hi_error.dart';
import 'dart:math' as math;
import '../http/dao/ranking_dao.dart';
import '../http/model/ranking_mo.dart';
import '../http/model/video_model.dart';
import '../util/toast.dart';

class FavoritePage extends StatefulWidget {
  const FavoritePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _FavoritePageState();
  }
}

class _FavoritePageState extends State<FavoritePage> {
  final List<VideoModel> _videoList = List.empty(growable: true);
  final ScrollController _scrollController = ScrollController();

  bool _isLoading = false;
  bool _isLastPage = false;
  int _pageIndex = 1;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);
    _loadData();
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      setState(() {
        _isLoading = true;
      });
      _loadData(loadMore: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("收藏"),
      ),
      body: RefreshIndicator(
        onRefresh: _loadData,
        child: CustomScrollView(
          controller: _scrollController,
          slivers: [
            SliverPadding(
                padding: const EdgeInsets.only(left: 5, right: 5),
                sliver: SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      final int itemIndex = index ~/ 2;

                      if (itemIndex == _videoList.length) {
                        logger.i("current index is $itemIndex");
                        if (_isLoading) {
                          return _noLoading();
                        }
                        if (_isLastPage) {
                          return _noMoreData();
                        }
                      } else {
                        final item = _videoList[itemIndex];
                        if (index.isEven) {
                          return VideoDetailCard(item);
                        }
                        return const Divider();
                      }
                      return null;
                    },
                    childCount: _computeActualChildCount(
                        _videoList.length + (_isLoading ? 1 : 0)),
                  ),
                )),
          ],
        ),
      ),
    );
  }

  int _computeActualChildCount(int itemCount) {
    return math.max(0, itemCount * 2 - 1);
  }

  _noLoading() {
    return const Center(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: CircularProgressIndicator(
          color: primary,
        ),
      ),
    );
  }

  _noMoreData() {
    return const Center(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Text("没有更多了！"),
      ),
    );
  }

  Future<void> _loadData({bool loadMore = false}) async {
    try {
      if (loadMore) {
        if (!_isLastPage) {
          _pageIndex++;
        }
      } else {
        _isLastPage = false;
        _pageIndex = 1;
        _videoList.clear();
      }
      RankingMo data =
          await RankingDao.get("favorite", pageIndex: _pageIndex, pageSize: 10);
      if (!_isLastPage) {
        _videoList.addAll(data.list);
      }
      if (data.list.length < 10) {
        _isLastPage = true;
      } else {
        _isLastPage = false;
      }

      setState(() {
        _isLoading = false;
      });
    } on NeedLogin catch (e) {
      showToast(e.message);
    } on HiNetError catch (e) {
      showToast(e.message);
    }
  }
}
